package org.example.util;

public class ShortSnowflakeIdGenerator {
    // 开始时间戳(2020-01-01)
    private final long twepoch = 1577836800000L;
    
    // 机器ID所占的位数
    private final long workerIdBits = 3L; // 最多支持8台机器
    
    // 序列号所占的位数
    private final long sequenceBits = 5L; // 每台机器每毫秒最多生成32个ID
    
    // 支持的最大机器ID
    private final long maxWorkerId = ~(-1L << workerIdBits);
    
    // 机器ID向左移的位数
    private final long workerIdShift = sequenceBits;
    
    // 时间戳向左移的位数
    private final long timestampLeftShift = sequenceBits + workerIdBits;
    
    // 序列号掩码
    private final long sequenceMask = ~(-1L << sequenceBits);
    
    // 工作机器ID(0~7)
    private long workerId;
    
    // 毫秒内序列号(0~31)
    private long sequence = 0L;
    
    // 上次生成ID的时间戳
    private long lastTimestamp = -1L;

    public ShortSnowflakeIdGenerator(long workerId) {
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(
                    String.format("workerId can't be greater than %d or less than 0", maxWorkerId));
        }
        this.workerId = workerId;
    }

    public synchronized long nextId() {
        long timestamp = timeGen();
        
        // 如果当前时间小于上一次ID生成的时间戳，说明系统时钟回退过，抛出异常
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(
                    String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", 
                            lastTimestamp - timestamp));
        }
        
        // 如果是同一毫秒内生成的，则进行毫秒内序列自增
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            // 毫秒内序列溢出
            if (sequence == 0) {
                // 阻塞到下一毫秒，获得新的时间戳
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            // 时间戳改变，毫秒内序列重置
            sequence = 0L;
        }
        
        // 上次生成ID的时间戳
        lastTimestamp = timestamp;
        
        // 移位并通过或运算拼到一起组成最终的ID
        return ((timestamp - twepoch) << timestampLeftShift) 
                | (workerId << workerIdShift) 
                | sequence;
    }
    
    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }
    
    protected long timeGen() {
        return System.currentTimeMillis();
    }

}